package p03_SingleLinkedList.quiz.q05_剑指OfferII078_合并排序链表;


import org.junit.jupiter.api.Test;

//Definition for singly-linked list.
public class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        if (lists.length == 0) {
            return null;
        }
        ListNode dummy = null;
        for (int i = 0; i < lists.length; i++) {
            dummy = merge2Lists2(dummy, lists[i]);
        }

        return dummy;
    }

    public ListNode merge2Lists1(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        ListNode dummy = new ListNode();
        ListNode temp0 = dummy;
        ListNode temp1 = l1;
        ListNode temp2 = l2;
        while (l1 != null && l2 != null) {
            if (l1.val <= l2.val) {
                temp0.next = temp1;
                temp1 = temp1.next;
            } else {
                temp0.next = temp2;
                temp2 = temp2.next;
            }
            temp0 = temp0.next;
        }

        if (temp1 == null) {
            temp0.next = temp2;
        } else {
            temp0.next = temp1;
        }
        return dummy.next;
    }

    public ListNode merge2Lists2(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        if (l1.val <= l2.val) {
            l1.next = merge2Lists2(l1.next, l2);
            return l1;
        } else {
            l2.next = merge2Lists2(l1, l2.next);
            return l2;
        }
    }

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        if (l1.val <= l2.val) {
            l1.next = mergeTwoLists(l1.next, l2);
            return l1;
        } else {
            l2.next = mergeTwoLists(l1, l2.next);
            return l2;
        }
    }

    @Test
    public void test01() {
        ListNode l1 = new ListNode(1);
        l1.next = new ListNode(4);
        l1.next.next = new ListNode(5);

        ListNode l2 = new ListNode(1);
        l2.next = new ListNode(3);
        l2.next.next = new ListNode(4);

        ListNode l3 = new ListNode(2);
        l3.next = new ListNode(6);

        ListNode[] arr = new ListNode[]{l1, l2, l3};
        ListNode temp = mergeKLists(arr);
    }

    @Test
    public void test02() {
        ListNode l1 = new ListNode(1);
        l1.next = new ListNode(4);
        l1.next.next = new ListNode(5);

        ListNode l2 = new ListNode(1);
        l2.next = new ListNode(3);
        l2.next.next = new ListNode(4);
        ListNode temp = merge2Lists2(l1, l2);
    }
}
